<?php
class Encrypt {

    private static $encrypt = null;

    public static function getInstance() {
        if ( self::$encrypt == null ) {
            self::$encrypt = new Encrypt();
        }
        return self::$encrypt;
    }

    public function _encode( $txt, $key ) {
        srand( (double)microtime() * 1000000 );
        $encrypt_key = md5( rand( 0, 32000 ) );
        $ctr = 0;
        $tmp = '';
        for ( $i = 0; $i < strlen( $txt ); $i++ ) {
            $ctr = $ctr == strlen( $encrypt_key ) ? 0 : $ctr;
            $tmp .= $encrypt_key[ $ctr ] . ( $txt[ $i ] ^ $encrypt_key[ $ctr++ ] );
        }
        return base64_encode( $this->_key( $tmp, $key ) );
    }

    public function _decode( $txt, $key ) {
        $txt = $this->_key( base64_decode( $txt ), $key );
        $tmp = '';
        for ( $i = 0; $i < strlen( $txt ); $i++ ) {
            $md5 = $txt[ $i ];
            $tmp .= $txt[ ++$i ] ^ $md5;
        }
        return $tmp;
    }

    private function _key( $txt, $encrypt_key ) {
        $encrypt_key = md5( $encrypt_key );
        $ctr = 0;
        $tmp = '';
        for ( $i = 0; $i < strlen( $txt ); $i++ ) {
            $ctr = $ctr == strlen( $encrypt_key ) ? 0 : $ctr;
            $tmp .= $txt[ $i ] ^ $encrypt_key[ $ctr++ ];
        }
        return $tmp;
    }

    public function _md5( $str, $key ) {
        $mds = md5( $str . $key );
        $md_asc = '';
        for ( $i = 1; $i < strlen( $mds ); $i++ ) {
            $md_asc .= 168 / ord( substr( $mds, $i, 1 ) );
        }
        return md5( $md_asc . $this->_key( $str, $key ) );
    }
}